﻿using System;
using System.Collections.Generic;
using System.Globalization;
using System.Text;
using System.Windows;
using System.Windows.Controls;
using System.Windows.Data;
using System.Windows.Documents;
using System.Windows.Input;
using System.Windows.Media;
using System.Windows.Media.Imaging;
using System.Windows.Navigation;
using System.Windows.Shapes;

namespace WpfApp5_StackPanel.Model
{
    /// <summary>
    /// 按照步骤 1a 或 1b 操作，然后执行步骤 2 以在 XAML 文件中使用此自定义控件。
    ///
    /// 步骤 1a) 在当前项目中存在的 XAML 文件中使用该自定义控件。
    /// 将此 XmlNamespace 特性添加到要使用该特性的标记文件的根
    /// 元素中:
    ///
    ///     xmlns:MyNamespace="clr-namespace:WpfApp5_StackPanel.Model"
    ///
    ///
    /// 步骤 1b) 在其他项目中存在的 XAML 文件中使用该自定义控件。
    /// 将此 XmlNamespace 特性添加到要使用该特性的标记文件的根
    /// 元素中:
    ///
    ///     xmlns:MyNamespace="clr-namespace:WpfApp5_StackPanel.Model;assembly=WpfApp5_StackPanel.Model"
    ///
    /// 您还需要添加一个从 XAML 文件所在的项目到此项目的项目引用，
    /// 并重新生成以避免编译错误:
    ///
    ///     在解决方案资源管理器中右击目标项目，然后依次单击
    ///     “添加引用”->“项目”->[浏览查找并选择此项目]
    ///
    ///
    /// 步骤 2)
    /// 继续操作并在 XAML 文件中使用控件。
    ///
    ///     <MyNamespace:CustomYButton/>
    ///
    /// </summary>
    public class CustomYButton : Control
    {
        FormattedText formtxt;
        bool isMouseReallyOver;

        public static readonly DependencyProperty TextProperty;
        public static readonly RoutedEvent YclickEvent;
        public static readonly RoutedEvent PreviewYclickEvent;
        static CustomYButton()
        {
            TextProperty = DependencyProperty.Register("Text", typeof(string), typeof(CustomYButton),
                new FrameworkPropertyMetadata(" ", FrameworkPropertyMetadataOptions.AffectsMeasure));
            YclickEvent = EventManager.RegisterRoutedEvent("Yclick", RoutingStrategy.Bubble,
                typeof(RoutedEventHandler), typeof(CustomYButton));
            PreviewYclickEvent = EventManager.RegisterRoutedEvent("PreviewYclick", RoutingStrategy.Tunnel,
                typeof(RoutedEventHandler), typeof(CustomYButton));

            //DefaultStyleKeyProperty.OverrideMetadata(typeof(CustomYButton),
            //    new FrameworkPropertyMetadata(typeof(CustomYButton)));
        }

        public string Text
        {
            get { return (string)GetValue(TextProperty); }
            set { SetValue(TextProperty, value == null ? " ": value); }
        }

        public event RoutedEventHandler Yclick
        {
            add { AddHandler(YclickEvent, value); }
            remove { RemoveHandler(YclickEvent, value); }
        }
        public event RoutedEventHandler PreviewYclick
        {
            add { AddHandler(PreviewYclickEvent, value); }
            remove { RemoveHandler(PreviewYclickEvent, value); }
        }

        //[Obsolete]
        protected override Size MeasureOverride(Size constraint)
        {
            formtxt = new FormattedText(Text, CultureInfo.CurrentCulture, FlowDirection,
                new Typeface(FontFamily, FontStyle, FontWeight, FontStretch), FontSize, Foreground);

            Size sizeDesired = new Size(Math.Max(48, formtxt.Width) + 4, formtxt.Height +4);
            sizeDesired.Width += Padding.Left + Padding.Right;
            sizeDesired.Height += Padding.Top + Padding.Bottom;
            return sizeDesired;
            //return base.MeasureOverride(constraint);
        }

        protected override void OnRender(DrawingContext drawingContext)
        {
            Brush brushBackground = SystemColors.ControlBrush;
            if (isMouseReallyOver && IsMouseCaptured)
            {
                brushBackground = SystemColors.ControlDarkBrush;
            }
            Pen pen = new Pen(Foreground, IsMouseOver ? 2 : 1);
            drawingContext.DrawRoundedRectangle(brushBackground, pen, new Rect(new Point(0, 0), RenderSize), 4, 4);

            formtxt.SetForegroundBrush(IsEnabled ? Foreground : SystemColors.ControlDarkBrush);
            Point ptText = new Point(2, 2);
            switch (HorizontalContentAlignment)
            {
                case HorizontalAlignment.Left:
                    {
                        ptText.X += Padding.Left;
                    }
                    break;
                case HorizontalAlignment.Right:
                    {
                        ptText.X += RenderSize.Width - formtxt.Width - Padding.Right;
                    }
                    break;
                case HorizontalAlignment.Center:
                case HorizontalAlignment.Stretch:
                    {
                        ptText.X += (RenderSize.Width - formtxt.Width - Padding.Left - Padding.Right) / 2;
                    }
                    break;
            }
            switch (VerticalContentAlignment)
            {
                case VerticalAlignment.Top:
                    {
                        ptText.Y += Padding.Top;
                    }
                    break;
                case VerticalAlignment.Bottom:
                    {
                        ptText.Y += RenderSize.Height - formtxt.Height - Padding.Bottom;
                    }
                    break;
                case VerticalAlignment.Center:
                case VerticalAlignment.Stretch:
                    {
                        ptText.Y += (RenderSize.Height - formtxt.Height - Padding.Top - Padding.Bottom) / 2;
                    }
                    break;
            }
            drawingContext.DrawText(formtxt, ptText);

            base.OnRender(drawingContext);
        }

        protected override void OnMouseEnter(MouseEventArgs e)
        {
            base.OnMouseEnter(e);
            InvalidateVisual();
        }

        protected override void OnMouseLeave(MouseEventArgs e)
        {
            base.OnMouseLeave(e);
            InvalidateVisual();
        }

        protected override void OnMouseMove(MouseEventArgs e)
        {
            base.OnMouseMove(e);
            Point pt = e.GetPosition(this);
            bool isReallyOverNow = (pt.X >= 0 && pt.X < ActualHeight && pt.Y >=0 && pt.Y < ActualHeight);
            if (isReallyOverNow != isMouseReallyOver)
            {
                isMouseReallyOver = isReallyOverNow;
                InvalidateVisual();
            }
        }

        protected override void OnMouseLeftButtonDown(MouseButtonEventArgs e)
        {
            base.OnMouseLeftButtonDown(e);

            CaptureMouse();
            InvalidateVisual();
            e.Handled = true;
        }

        protected override void OnMouseLeftButtonUp(MouseButtonEventArgs e)
        {
            base.OnMouseLeftButtonUp(e);
            if (IsMouseCaptured)
            {
                if (isMouseReallyOver)
                {
                    OnPreviewYclick();
                    OnYclick();
                }
                e.Handled = true;
                Mouse.Capture(null);
            }
        }

        protected override void OnLostMouseCapture(MouseEventArgs e)
        {
            base.OnLostMouseCapture(e);
            InvalidateVisual();
        }

        protected override void OnKeyDown(KeyEventArgs e)
        {
            base.OnKeyDown(e);
            if (e.Key == Key.Space || e.Key == Key.Enter)
            {
                e.Handled = true;
            }
        }

        protected override void OnKeyUp(KeyEventArgs e)
        {
            base.OnKeyUp(e);
            if (e.Key == Key.Space || e.Key == Key.Enter)
            {
                OnPreviewYclick();
                OnYclick();
                e.Handled = true;
            }
        }

        protected virtual void OnYclick()
        {
            RoutedEventArgs args = new RoutedEventArgs();
            args.RoutedEvent = CustomYButton.YclickEvent;
            args.Source = this;
            RaiseEvent(args);
        }
        protected virtual void OnPreviewYclick()
        {
            RoutedEventArgs args = new RoutedEventArgs
            {
                RoutedEvent = CustomYButton.PreviewYclickEvent,
                Source = this
            };
            RaiseEvent(args);
        }
    }
}
